﻿using System;
using System.Collections.Generic;
using SrBBSPro.Entities;

namespace SrBBSPro.BaseClasses
{
    public class BaseUserService<T> : BaseService<T, string> where T : BaseUserEntity
    {
        
        public T GetEntityWithUser(string userId)
        {
            var obj = DbBase.Query<T>().Include(t => t.User).Where(t => t.Id == userId).SingleOrDefault();
            if (obj == null)
            {
                obj = Activator.CreateInstance<T>();
                obj.User = GetUserInfo(userId);
                obj.Id = userId;
            }
            return obj;
        }

        public List<T> GetListWithUser()
            => DbBase.Query<T>().Include(t => t.User).ToList();

        public override Response InsertOrUpdate(object obj)
        {
            var response = new Response();
            var entity = Activator.CreateInstance<T>();
            if (obj == null)
                throw new ArgumentNullException(nameof(entity));
            try
            {
                entity.SetProp(obj);
                using (var transaction = DbBase.GetTransaction())
                {
                    string tabId = string.Empty;
                    int num = 0;
                    //TO-DO 双主键
                    if (GetSingleEntity(entity.Id) == null)
                    {
                        tabId=Convert.ToString(DbBase.Insert(entity));
                    }
                    else
                    {
                        num= DbBase.Update(entity);
                    }
                    if(!string.IsNullOrEmpty(tabId) || num > 0)
                    {
                        response.IsSuccess = true;
                        response.Message = "操作成功";
                    }
                    else
                    {
                        response.Message = "操作失败";
                    }
                    transaction.Complete();
                }
            }
            catch
            {
                response.Message = "操作失败";
            }
            return response;
        }
    }
}
